package com.qfedu.yanglao20admin.camera.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qfedu.yanglao20.common.constants.CommonConstants;
import com.qfedu.yanglao20.common.exeception.CommonException;
import com.qfedu.yanglao20.entity.camera.CameraType;
import com.qfedu.yanglao20admin.camera.dao.CameraTypeDao;
import com.qfedu.yanglao20admin.camera.param.CameraTypeParam;
import com.qfedu.yanglao20admin.camera.service.CameraTypeService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class CameraTypeServiceImpl implements CameraTypeService {

    @Resource
    private CameraTypeDao cameraTypeDao;

    @Override
    public List<CameraType> selectList() {
        return cameraTypeDao.selectTypeAll();
    }

    @Override
    public Page<CameraType> pageCameraType(CameraTypeParam param) {
        // 计算偏移量
        Integer offset = (param.getPageNum() - 1) * param.getPageSize();
        param.setOffset(offset);

        //分页查询
        Page<CameraType> page = new Page<>(param.getPageNum(), param.getPageSize());
        List<CameraType> cameraTypes = cameraTypeDao.selectList(param);

        //页码
        page.setCurrent(param.getPageNum());
        //每页查询的记录数
        page.setSize(param.getPageSize());
        //总记录数
        Long aLong = cameraTypeDao.selectCount(null);
        page.setTotal(aLong);
        page.setRecords(cameraTypes);
        return page;
    }

    @Override
    public void deleteById(Integer id) {
        cameraTypeDao.deleteById(id);
    }

    @Override
    public CameraType selectById(Integer id) {
        return cameraTypeDao.selectById(id);
    }

    @Override
    public void insertCameraType(CameraType cameraType) {
        if (cameraType.getCameraType() == null || cameraType.getCameraType().isEmpty()) {
            throw new CommonException(CommonConstants.ERROR, "请填写摄像头类型");
        }

        CameraType cameraType1 = cameraTypeDao.selectByName(cameraType.getCameraType());
        if (cameraType1 != null) {
            throw new CommonException(CommonConstants.ERROR, "该摄像头类型已存在");
        }

        cameraTypeDao.insert(cameraType);
    }

    @Override
    public void updateCameraType(CameraType cameraType) {
        if (cameraType.getCameraType() == null || cameraType.getCameraType().isEmpty()) {
            throw new CommonException(CommonConstants.ERROR, "请填写摄像头类型");
        }

        CameraType cameraType1 = cameraTypeDao.selectByName(cameraType.getCameraType());
        if (cameraType1 != null) {
            if (!cameraType1.getId().equals(cameraType.getId())) {
                throw new CommonException(CommonConstants.ERROR, "该摄像头类型已存在");
            }
        }

        cameraTypeDao.updateById(cameraType);
    }
}
